package com.yrh.dao.impl;

import com.yrh.bean.TUser;
import com.yrh.dao.TUserDao;
import com.yrh.utils.DataSourceUtil;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
/*用户数据层接口实现类*/
public class TUserDaoImpl implements TUserDao {
    private JdbcTemplate temp=new JdbcTemplate(DataSourceUtil.getDataSource());
    //用户登录
    @Override
    public TUser login(TUser tUser) {
        try {
            return temp.queryForObject("select * from t_user where user_tel=? and user_pwd=?",new BeanPropertyRowMapper<TUser>(TUser.class),
                    tUser.getUserTel(),tUser.getUserPwd());
        } catch (Exception e) {
            return null;
        }

    }
    //查询所有用户(分页)
    @Override
    public List<TUser> allTUser(TUser tUser,int nowPage,int size) {
        String sql="SELECT * FROM t_user where 1=1";
        List<String> list=new ArrayList<>();
        if (tUser.getBeginTime()!=null&&!"".equals(tUser.getBeginTime())){
            sql += " and add_time >= ?";
            list.add(tUser.getBeginTime());
        }
        if (tUser.getEndTime()!=null&&!"".equals(tUser.getEndTime())){
            sql += " and add_time <= ?";
            list.add(tUser.getEndTime());
        }
        if (tUser.getUserTel()!=null&&!"".equals(tUser.getUserTel())){
            sql += " and  user_tel = ?";
            list.add(tUser.getUserTel());
        }
        if (size!=0){
            sql+=" limit "+(nowPage-1)*size+","+size;
        }
        return temp.query(sql,list.toArray(),new BeanPropertyRowMapper<>(TUser.class));
    }


    //判断手机号是否存在
    @Override
    public TUser getUserByTel(TUser tUser) {
        try {
            return temp.queryForObject("SELECT * FROM t_user WHERE user_tel=?",new BeanPropertyRowMapper<>(TUser.class),tUser.getUserTel());
        } catch (Exception e) {
           return null;
        }
    }
   /*添加用户*/
    @Override
    public int addTUser(TUser user) {
        return temp.update("insert into t_user(user_tel,user_pwd,user_name,user_sex) values(?,?,?,?)",user.getUserTel(),user.getUserPwd(),
                user.getUserName(),user.getUserSex());
    }
    //修改用户信息(用户名和性别)
    @Override
    public int updateTUser(TUser tUser) {
        //修改账号
        if (tUser.getUserName()!=null&&!"".equals(tUser.getUserName())){
            return temp.update("update t_user set user_name=?,user_sex=? where user_id=?",tUser.getUserName(),tUser.getUserSex(),tUser.getUserId());
        }else if (tUser.getUserStatus()!=null){//修改用户状态
            return temp.update("UPDATE t_user SET user_status=? WHERE user_id=?",tUser.getUserStatus(),tUser.getUserId());
        }
        //修改密码
       else return temp.update("update t_user set user_pwd=? where user_id=?",tUser.getUserPwd(),tUser.getUserId());

    }
}
